<template>
	<view style="padding: 20rpx;">
		<view class="box">
			<uni-forms :modelValue="form" :rules="rules" ref="formRef" label-width="140rpx" label-align="right">
				
				<!-- 旧密码 -->
				<uni-forms-item label="旧密码" name="oldPassword">
					<uni-easyinput type="password" v-model="form.oldPassword" placeholder="请输入旧密码" />
				</uni-forms-item>

				<!-- 新密码 -->
				<uni-forms-item label="新密码" name="newPassword">
					<uni-easyinput type="password" v-model="form.newPassword" placeholder="请输入新密码" />
				</uni-forms-item>

				<!-- 确认新密码 -->
				<uni-forms-item label="确认新密码" name="confirmPassword">
					<uni-easyinput type="password" v-model="form.confirmPassword" placeholder="请再次输入新密码" />
				</uni-forms-item>

				<!-- 保存按钮 -->
				<uni-forms-item>
					<button type="primary" size="mini" @click="save">保 存</button>
				</uni-forms-item>
			</uni-forms>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					oldPassword: '',
					newPassword: '',
					confirmPassword: ''
				},
				user: uni.getStorageSync('xm-user'), // 从缓存中获取用户信息
				rules: {
					oldPassword: {
						required: true,
						message: '请输入旧密码',
						trigger: ['blur', 'change']
					},
					newPassword: {
						required: true,
						message: '请输入新密码',
						trigger: ['blur', 'change']
					},
					confirmPassword: {
						required: true,
						validator: (rule, value, callback) => {
							if (value !== this.form.newPassword) {
								callback(new Error('两次输入的新密码不一致'))
							} else {
								callback()
							}
						},
						trigger: ['blur', 'change']
					}
				}
			}
		},
		methods: {
			// 保存新密码
			save() {
				this.$refs.formRef.validate(valid => {


					// 判断新密码和确认密码是否一致
					if (this.form.newPassword !== this.form.confirmPassword) {
						uni.showToast({
							icon: "error",
							title: '两次新密码输入不一致'
						});
						return;
					}

					// 判断用户身份，发送不同请求
					let url = '';
					if (this.user.role === 'teacher') {
						url = '/teacher/password';
					} else {
						url = '/user/password';
					}

					// 发起请求，发送旧密码、新密码、账号
					this.$request.post(url, {
						account: this.user.account,
						newPassword: this.form.newPassword
					}).then(res => {
						if (res.code === '200') {
							uni.showToast({
								icon: "success",
								title: '密码修改成功'
							});
						} else {
							uni.showToast({
								icon: "error",
								title: res.msg
							});
						}
					});
				});
			}
		}
	}
</script>


<style>
</style>
